package com.herr.springboot.self.xxx.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.herr.springboot.self.xxx.common.anno.NoLogin;
import com.herr.springboot.self.xxx.common.enums.ApiResultEnum;
import com.herr.springboot.self.xxx.common.util.JwtUtils;
import com.herr.springboot.self.xxx.model.entity.User;
import com.herr.springboot.self.xxx.model.query.PageQuery;
import com.herr.springboot.self.xxx.model.query.UserQuery;
import com.herr.springboot.self.xxx.common.entity.ApiResult;
import com.herr.springboot.self.xxx.common.entity.Principal;
import com.herr.springboot.self.xxx.common.exception.BizException;
import com.herr.springboot.self.xxx.model.dto.UserDTO;
import com.herr.springboot.self.xxx.service.IUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户表 前端控制器
 *
 * @author herr05
 */
@Slf4j
@Api(tags = {"User"}, description = "用户表相关接口")
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     * @param userQuery
     * @return
     */
    @NoLogin
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usercode", value = "账号", paramType = "query", required=true,defaultValue = "herr05"),
            @ApiImplicitParam(name = "pwd", value = "密码", paramType = "query", required=true,defaultValue = "111111")
    })
    @GetMapping("/login")
    public ApiResult login(@Validated UserQuery userQuery){
        String pwdMd5 = SecureUtil.md5(userQuery.getPwd());
        User user =userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsercode, userQuery.getUsercode())
                .eq(User::getPwd,SecureUtil.md5(userQuery.getPwd()))
        );
        if (user ==null){
            return new ApiResult<>().fail(ApiResultEnum.ACCOUNT_ERR);
        }
        String token= JwtUtils.generateToken(user);
        return new ApiResult<>(token);

    }

    /**
     * 添加用户
     * @param userQuery
     * @return
     */
    @ApiOperation("添加用户")
    @PutMapping("")
    public ApiResult addUser(@Validated UserQuery userQuery){
        int count=userService.count(Wrappers.<User>lambdaQuery()
                .eq(User::getUsercode, userQuery.getUsercode()));
        if (count>0){
            throw new BizException("请勿重复添加相同用户");
        }
        User user=new User();
        user.setUsercode(userQuery.getUsercode());
        user.setPwd(SecureUtil.md5(userQuery.getPwd()));
        userService.save(user);
        log.info("插入后的主键id："+ user.getId().toString());
        return new ApiResult<>();
    }


    /**
     * 查询某用户信息
     * @param userId
     * @return
     */
    @ApiOperation("查询某用户信息")
    @GetMapping("/{userId}")
    public ApiResult getUser(@PathVariable("userId") Integer userId){
        User user =userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId,userId)
                .eq(User::getDelFlag,0));
        return new ApiResult<>(user);
    }

    /**
     * 删除某用户
     * @param userId
     * @return
     */
    @ApiOperation("删除某用户")
    @DeleteMapping("/{userId}")
    public ApiResult deleteUser(@PathVariable("userId") Integer userId){
        boolean isSuccess = userService.update(Wrappers.<User>lambdaUpdate()
                .eq(User::getId,userId)
                .set(User::getDelFlag,1)
                .set(User::getUpdateTime, LocalDateTime.now()));
        return new ApiResult<>();
    }

    /**
     * 查询登录者的用户信息
     * @param principal principal为token解析后统一处理后的入参，包含JWT请求封装的鉴权信息
     * @return
     */
    @ApiOperation("查询登录者的用户信息")
    @GetMapping("/getLoginUser")
    public ApiResult getLoginUser(Principal principal){
        System.out.println(principal.getUid());
        User user =userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId,principal.getUid())
                .select(User::getId,User::getUsercode,User::getUsername,User::getDeptName));
        return new ApiResult<>(user);
    }

    /**
     *
     * @param principal
     * @param pageVo 分页
     * @return
     */
    @ApiOperation("查询用户列表（分页）")
    @GetMapping("/listPage")
    public ApiResult listPage(Principal principal, @Validated PageQuery pageVo){
        IPage<UserDTO> pages = userService.listPage(pageVo,"集团平台部");
        List<UserDTO> userList=pages.getRecords();
        return new ApiResult<>(userList);
    }

    @NoLogin
    @GetMapping("/setSession")
    public ApiResult setSession(HttpServletRequest request){
        User user = new User();
        user.setUsername("何荣荣");
        user.setUsercode("herr");
        request.getSession().setAttribute("user",user);
        return new ApiResult<>("test");
    }

    @NoLogin
    @GetMapping("/getSession")
    public ApiResult getSession(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        return new ApiResult<>(user);
    }


}
